import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET() {
  try {
    // 获取热门商品（根据订单数量排序）
    const popularCommodities = await prisma.commodity.findMany({
      select: {
        goodsId: true,
        goodsName: true,
        ImgUrl: true,
        goodsPrice: true,
        _count: {
          select: {
            orders: true, // 统计每个商品的订单数量
          },
        },
      },
      orderBy: {
        orders: {
          _count: 'desc', // 按订单数量降序排列
        },
      },
      take: 4,
    });

    return NextResponse.json(
      { popularCommodities },
      { status: 200 }
    );
  } catch (error) {
    console.error("获取热门商品数据失败:", error);
    return NextResponse.json({ error: "获取热门商品数据失败" }, { status: 500 });
  }
}